<?php

namespace web\admin\controller;

class Category extends Common{
    private $db;
    public function __construct()
    {
        parent::__construct();
        $this->db=new \system\model\Category();
    }

    //分类管理
	public function index(){
		//分类
        $data=Data::tree($this->db->orderBy('cid','ASC')->get(),'cname');
        $typedata=Db::table('type')->get();
//        p($typedata);die;
        View::with('$typedata',$typedata);
        View::with('olddata',$data)->make();
	}
    //分类添加)
    public function add(){
        if(IS_POST){
            if($this->db->store()){
                message('添加成功','','success');
            }else{
                message($this->db->getError(),'back','error');
            }
        }
        View::make();
    }
    //添加子分类
    public function add_son(){
        $pid=q('get.cid',0,'intval');
        $_POST['pid']=$pid;
        //p($_POST);die;
        if(IS_POST){
            if($this->db->add_son()){
                message('添加子类成功',u('index'),'success');
            }else{
                message($this->db->getError(),'back','error');
            }
        }

        $typedata=Db::table('type')->get();
        //p($typedata);die;
        $catename=$this->db->where('cid',$pid)->pluck('cname');
        //p($catename);die;
        View::with('typedata',$typedata)->with('catename',$catename)->make();
    }
    //编辑分类
    public function edit(){
        if(IS_POST){
            if($this->db->edit()){
                message('修改成功','','success');
            }else{
                message($this->db->getError(),'back','error');
            }
        }

        $cid=q('get.cid',0,'intval');
        $catedata=$this->db->getfu($cid);
        //p($catedata);die;
        $typedata=Db::table('type')->get();
        $olddata=$this->db->where('cid',$cid)->first();
        //p($olddata);die;
        View::with('typedata',$typedata)->with('cid',$cid)->with('olddata',$olddata)->with('catedata',$catedata)->make();
    }
    //删除分类
    public function del(){
        $cid=q('get.cid',0,'intval');
        //p($cid);die;
        //把子类向上提一级，此cid所对应的pid把pid赋值给他的儿子
        $pid=$this->db->where('cid',$cid)->pluck('pid');//pluck为获取单一字段
        //p($pid);die;
        //找到当前cid的儿子
        $this->db->where('pid',$cid)->update(['pid'=>$pid]);
        //删除当前的cid所对应的内容
        $this->db->where('cid',$cid)->delete();
        message('删除成功','','success');
    }


}
